package com.splunk.hiring.imov.service;

import java.io.IOException;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.splunk.hiring.imov.entity.Movie;
import com.splunk.hiring.imov.entity.MovieDetail;
import com.splunk.hiring.imov.persist.db.MovieDao;

@Service
public class MovieDetailService {
	
	@Value("${movieservice.tmdb.api.key}")
	private String api_key;
	
	@Value("${movieservice.tmdb.api.address}")
	private String detail_address;
	
	@Value("${movieservice.tmdb.api.img.address}")
	private String img_address;
	
	@Autowired
	private HttpClient httpClient;
	
	@Autowired
	MovieDao movieDao;
	
	private Map<Long,MovieDetail> movieCacheMap = Maps.newHashMap();
	
	public MovieDetail getMovieDetail(Movie movie){
		
		Long movieId = movie.getId();
		if(movieCacheMap.containsKey(movieId)){
			return movieCacheMap.get(movieId);
		}
		
		Long tmdbId = movieDao.getTmdbIdByMovie(movie);
		String movieDetailUrl = this.getTMDBMovieUrl(tmdbId);
		HttpGet request = new HttpGet(movieDetailUrl);
		try {
			HttpResponse response = httpClient.execute(request);
			
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String strResult = EntityUtils.toString(response.getEntity());
                JSONObject jsonResult = JSONObject.parseObject(strResult);
                MovieDetail detail = new MovieDetail(movie);
                detail.setHomePage(jsonResult.getString("homepage"));
                detail.setOverview(jsonResult.getString("overview"));
                detail.setPoster_img(img_address+"/"+jsonResult.getString("poster_path"));
                detail.setReleaseDate(jsonResult.getString("release_date"));
                detail.setRunTime(jsonResult.getString("runtime"));
                detail.setTagLine(jsonResult.getString("tagline"));
                movieCacheMap.put(movieId, detail);
                return detail;
            } else {
            	//failure
            }			
			
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	private String getTMDBMovieUrl(Long tmdbId){
		return detail_address+"/"+tmdbId+"?api_key="+api_key;
	}
	
	
}
